<?php
use BaiduBce\BceClientConfigOptions;
use BaiduBce\Util\Time;
use BaiduBce\Util\MimeTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Services\Bos\BosClient;
use App\Model\VendorBill;
/*
 * 响应 json 封装
 * */
 // @TODO @cgz 解决 _ 占位的问题
function res($type, $msg = '', $data = ['_' => '_']) {
  // $validator
  if(gettype($msg) === 'object') {
    $msg = $msg -> errors() -> all()[0];
  }
  return response() -> json(
    array(
      'type' => $type,
      'msg' => $msg,
      'data' => $data
    )
  );
}
/*
 * 数据字典
 * */
function type(){
    //用户行为
    $type['user_action'] = [
        '1' => 'view',
        '2' => 'lottery',
        '3' => 'click'
    ];
    //红包顺序类型
    $type['event_gift_issuse_order_type'] = [
        1 => 'fixed',
        2 => 'random',
    ];

    //活动时间类型
    $type['event_time_type'] = [
        1 => 'day',
        2 => 'forever',
    ];
    //活动类型
    $type['event_type'] = [
        1 => 'code_in_commodity',
        2 => 'default',
    ];
    //活动抽奖次数类型
    $type['event_chance_type'] = [
        1 => 'day',
        2 => 'forever',
    ];
    //event_gift 红包金额类型
    $type['event_gift_red_pack_price'] = [
        1 => 'fixed',
        2 => 'random',
    ];
    //event_gift 红包中奖顺序
    $type['event_gift_red_pack_order'] = [
        1 => 'fixed',
        2 => 'random',
    ];
    // 1 必发式 2 收益式
    $type['event_gift_issuse_type'] = [
        1 => 'inevitable',
        2 => 'earnings',
    ];
    $type['recharge_type'] = [
        0 => 'wechat',
        1 => 'alipay',
        2 => 'remit',
        3 => 'earnings',
        4 => 'wechat_cash',
        5 => 'wechat_direct_cash',
    ];
    // 礼品类型
    $type['gift_type'] = [
        0 => 'wechat_cash', //微信红包
        1 => 'wechat_direct_cash', //微信直达红包
        2 => 'small_cash', //小额红包
        3 => 'coupon', //优惠券
        4 => 'non_physical_gift', //非实物礼品
        5 => 'physical_gift', //实物礼品
        6 => 'points', //积分
        7 => 'lottery', //福利彩票
    ];
    // 图片上传来源
    $type['pic_type'] = [
        0 => 'gift',//创建礼品图片
        1 => 'thanks',//谢谢惠顾
        2 => 'virtual', //虚拟奖品
    ];
    $type['cost_type'] = [
        0 => 'wechat_cash',
        1 => 'wechat_direct_cash',
    ];
    $type['bill_type'] = [
        0 => 'cost',
        1 => 'recharge',
    ];
    $type['order_status'] = [
        0 => '待付款',
        1 => '已付款',
        2 => '审核失败',
    ];
    $type['account_status'] = [
        0 => 'default',
        1 => 'success',
        2 => 'fail',
        3 => 'cancel',
    ];
    return $type;
}

/*
 * 获取最近七天的日期
 * */
function get_weeks($time = '', $format='Y-m-d'){
    $time = $time != '' ? $time : time();
    //组合数据
    $date = [];
    for ($i=1; $i<=7; $i++){
        $date[$i] = date($format ,strtotime( '+' . $i-7 .' days', $time));
    }
    return $date;
}

/*
 * 百度云
 * */
function bdBos($request){
    include '../app/Libs/baiduyun/BaiduBce.phar';
    require '../app/Libs/baiduyun/YourConf.php';
    $res = upload($request);
    if ($res['code'] == 200) {
        $BOS_TEST_CONFIG =
            array(
                'credentials' => array(
                    'accessKeyId' => env('BAIDUYUN_KEYID'),
                    'secretAccessKey' => env('BAIDUYUN_SKEY'),
                    // 'sessionToken' => 'your session token'
                ),
                'endpoint' => 'http://su.bcebos.com',
                'stsEndpoint' => 'http://sts.su.bcebos.com',
            );
        //新建BosClient
        $client = new BosClient($BOS_TEST_CONFIG);
        $bd_filename = md5_file($res['path']);
        $res = $client->putObjectFromFile('admpv-public', $bd_filename, $res['path']);
        $arr = json_decode(json_encode($res),true);
        if (empty($arr['metadata']['etag'])){
            return statusJson('fail');
        }
        $url = env('BAIDUYUN_URL').$arr['metadata']['etag'];
        return $data = ['status' => 'pass', 'url' => $url];
    }
    }
/*
 * uuid
 * */
function uuid(){
    return \Ramsey\Uuid\Uuid::uuid4();
}



/*
 * 生成随机数
 * */
function randStr($length)
{
    $pattern = '1234567890abcdefghijklmnopqrstuvwxyz
               ABCDEFGHIJKLOMNOPQRSTUVWXYZ';
    $str = '';
    for($i=0;$i<$length;$i++)
    {
        $str .= $pattern{mt_rand(0,35)};    //生成php随机数
    }
    return $str;
}
/*
 * 微信继续完成支付
 * */
function continueWxpay($order_id){
    $logHandler= new \CLogFileHandler('..' . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'Libs' . DIRECTORY_SEPARATOR . 'wxpay' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log');
    $log = \Log::Init($logHandler, 15);
    $notify = new \NativePay();
    $vendorRecharge = VendorBill::where('order_id', $order_id) -> first();
    if (empty($vendorRecharge)){
        return false;
    }
    $data = [
        'id' => $vendorRecharge -> order_id,
        'code_url' => $vendorRecharge -> code_url,
    ];
    return $data;
}


/*
 * 返回状态json
 * */
function statusJson($status, $msg = ''){
    if ($msg) {
        $data['msg'] = $msg;
    }
    $data['type'] = $status;
    return response() -> json($data);
}

/*
 * 返回数据json
 * */
function dataJson($status, $data){
    return response() -> json(['type' => $status, 'data' => $data]);
}

/*
 * 生成图片
 * */
function png($url){
    header('Content-Type:image/png');
    ob_clean();
    require_once '..'.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'Libs'.DIRECTORY_SEPARATOR.'wxpay'.DIRECTORY_SEPARATOR.'example'.DIRECTORY_SEPARATOR.'phpqrcode'.DIRECTORY_SEPARATOR.'phpqrcode.php';
    $url = urldecode($url);
    if(substr($url, 0, 6) == "weixin"){
       QRcode::png($url);
        exit;
    }else{
        header('HTTP/1.1 404 Not Found');
    }
}

/*
 * 微信支付返回结果
 * */
function returnPaySuccess()
{
    $string =   '<xml>
                <return_code><![CDATA[SUCCESS]]></return_code>
                <return_msg><![CDATA[OK]]></return_msg>
            </xml>';
    exit($string);
}

/*
 * 发送短信
 * */
function smsSend($num, $mobile){
    $postData = [
        'api_user' => env('MSM_USERNAME'),
        'api_pwd' => env('MSM_PASSWORD'),
        'mobiles' => $mobile,
        'sign' => '上量',
        'content' => '您的短信验证码是：'.$num
    ];
    $api = 'http://www.emailcar.net/v2/sms_send';
    return json_decode(httpRequest($api, $postData), true);
}

/*
 * 封装日志方法
 * */
function err_log($filename,$content){
    // @TODO 将错误日志，加到数据库，不存本地文件。
    $monolog = \Illuminate\Support\Facades\Log::getMonolog();
    $monolog->popHandler();
    \Illuminate\Support\Facades\Log::useDailyFiles(storage_path("logs/$filename/error.log"));
    \Illuminate\Support\Facades\Log::info($content);
}

/*
 * 文件上传
 * */
function upload($request){
    // 判断是否有必要去做上传
    if($request -> hasFile('file') && $request -> file('file') -> isValid()){

        // 先对文件进行常规重命名
        $filename = sha1(time() . rand(100000,999999)) . '.' . $request -> file('file') -> getClientOriginalExtension();
        // 保存文件
        Storage::disk('public') -> put($filename,file_get_contents($request -> file('file') -> path()));
        // 给出响应
        $response = ['code' => 200, 'path' => '../storage/app/public/' . $filename , 'filename' => $filename];
    }else{
        // 给出响应
        $response = ['code' => 201];
    }
    // 输出响应
    return $response;
}

/**
 * 获取客户端IP
 * @return string
 */
function get_ip(){
    //判断服务器是否允许$_SERVER
    if(isset($_SERVER)){
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $realip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }elseif(isset($_SERVER['HTTP_CLIENT_IP'])) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }else{
            $realip = $_SERVER['REMOTE_ADDR'];
        }
    }else{
        //不允许就使用getenv获取
        if(getenv("HTTP_X_FORWARDED_FOR")){
            $realip = getenv( "HTTP_X_FORWARDED_FOR");
        }elseif(getenv("HTTP_CLIENT_IP")) {
            $realip = getenv("HTTP_CLIENT_IP");
        }else{
            $realip = getenv("REMOTE_ADDR");
        }
    }
    if (false !== strpos($realip, ',')){
        $realip = explode(',', $realip);
    }
    $realip=is_array($realip)?$realip[0]:$realip;
    if($realip=='::1'){
        $realip='127.0.0.1';
    }
    return $realip;
}

/*
 * curl库
 * */
function httpRequest($api, $postData = array())
{
    //1.初始化
    $ch = curl_init();
    //2.配置
    //2.1设置请求地址
    curl_setopt($ch, CURLOPT_URL, $api);
    //2.2数据流不直接输出
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
    //2.3POST请求
    if ($postData) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    }
    //curl注意事项，如果发送的请求是https，必须要禁止服务器端校检SSL证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //3.发送请求
    $data = curl_exec($ch);
    //4.释放资源
    curl_close($ch);
    return $data;
}

/**
 * 判断用户访问方式
 * @return bool true 微信 | false 普通浏览器
 */
function visitPlatform(){
    //判断用户访问方式 微信 | 浏览器
    $ua = $_SERVER['HTTP_USER_AGENT'];
    //MicroMessenger 是android/iphone版微信所带的
    //Windows Phone 是winphone版微信带的  (这个标识会误伤winphone普通浏览器的访问)
    // if(strpos($ua, 'MicroMessenger') == false || strpos($ua, 'Windows Phone') == false) {
    if(strpos($ua, 'MicroMessenger') == false) {
      //来自普通浏览器访问
      return 'browser';
    } else {
      //来自微信浏览器访问
      return 'wechat';
    }
}
/**
 * 获取客户端浏览器信息
 * @param   null
 * @author  https://blog.jjonline.cn/phptech/168.html
 * @return  string
 */
function getBroswer()
{
    $sys = $_SERVER['HTTP_USER_AGENT'];  //获取用户代理字符串
    if (stripos($sys, "Firefox/") > 0) {
        preg_match("/Firefox\/([^;)]+)+/i", $sys, $b);
        $exp[0] = "Firefox";
        $exp[1] = $b[1];    //获取火狐浏览器的版本号
    } elseif (stripos($sys, "Maxthon") > 0) {
        preg_match("/Maxthon\/([\d\.]+)/", $sys, $aoyou);
        $exp[0] = "傲游";
        $exp[1] = $aoyou[1];
    } elseif (stripos($sys, "MSIE") > 0) {
        preg_match("/MSIE\s+([^;)]+)+/i", $sys, $ie);
        $exp[0] = "IE";
        $exp[1] = $ie[1];  //获取IE的版本号
    } elseif (stripos($sys, "OPR") > 0) {
        preg_match("/OPR\/([\d\.]+)/", $sys, $opera);
        $exp[0] = "Opera";
        $exp[1] = $opera[1];
    } elseif (stripos($sys, "Edge") > 0) {
        //win10 Edge浏览器 添加了chrome内核标记 在判断Chrome之前匹配
        preg_match("/Edge\/([\d\.]+)/", $sys, $Edge);
        $exp[0] = "Edge";
        $exp[1] = $Edge[1];
    } elseif (stripos($sys, "Chrome") > 0) {
        preg_match("/Chrome\/([\d\.]+)/", $sys, $google);
        $exp[0] = "Chrome";
        $exp[1] = $google[1];  //获取google chrome的版本号
    } elseif (stripos($sys, 'rv:') > 0 && stripos($sys, 'Gecko') > 0) {
        preg_match("/rv:([\d\.]+)/", $sys, $IE);
        $exp[0] = "IE";
        $exp[1] = $IE[1];
    } else {
        $exp[0] = "未知浏览器";
        $exp[1] = "";
    }
    return $exp[0] . '(' . $exp[1] . ')';
}
/**
 * 获取客户端操作系统信息,包括win10
 * @param   null
 * @author  https://blog.jjonline.cn/phptech/168.html
 * @return  string
 */
function getOS(){
    $agent = $_SERVER['HTTP_USER_AGENT'];
    $os = false;

    if (preg_match('/win/i', $agent) && strpos($agent, '95')) {
        $os = 'Windows 95';
    } else if (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90')) {
        $os = 'Windows ME';
    } else if (preg_match('/win/i', $agent) && preg_match('/98/i', $agent)) {
        $os = 'Windows 98';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent)) {
        $os = 'Windows Vista';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent)) {
        $os = 'Windows 7';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent)) {
        $os = 'Windows 8';
    }else if(preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent)) {
        $os = 'Windows 10';#添加win10判断
    }else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent)) {
        $os = 'Windows XP';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent)) {
        $os = 'Windows 2000';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent)) {
        $os = 'Windows NT';
    } else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent)) {
        $os = 'Windows 32';
    } else if (preg_match('/linux/i', $agent)) {
        $os = 'Linux';
    } else if (preg_match('/unix/i', $agent)) {
        $os = 'Unix';
    } else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent)) {
        $os = 'SunOS';
    } else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent)) {
        $os = 'IBM OS/2';
    } else if (preg_match('/Mac/i', $agent) && preg_match('/PC/i', $agent)) {
        $os = 'Macintosh';
    } else if (preg_match('/PowerPC/i', $agent)) {
        $os = 'PowerPC';
    } else if (preg_match('/AIX/i', $agent)) {
        $os = 'AIX';
    } else if (preg_match('/HPUX/i', $agent)) {
        $os = 'HPUX';
    } else if (preg_match('/NetBSD/i', $agent)) {
        $os = 'NetBSD';
    } else if (preg_match('/BSD/i', $agent)) {
        $os = 'BSD';
    } else if (preg_match('/OSF1/i', $agent)) {
        $os = 'OSF1';
    } else if (preg_match('/IRIX/i', $agent)) {
        $os = 'IRIX';
    } else if (preg_match('/FreeBSD/i', $agent)) {
        $os = 'FreeBSD';
    } else if (preg_match('/teleport/i', $agent)) {
        $os = 'teleport';
    } else if (preg_match('/flashget/i', $agent)) {
        $os = 'flashget';
    } else if (preg_match('/webzip/i', $agent)) {
        $os = 'webzip';
    } else if (preg_match('/offline/i', $agent)) {
        $os = 'offline';
    } else {
        $os = '未知操作系统';
    }
    return $os;
}


/**
 * 获取跳转统计链接
 * 对应路由 /redirect  所对应的控制器
 */
function getRedirectUrl($url){
  return '/redirect/?url=' . urlencode($url);
}

function apiGiftCreate () {
  return 1;
}

use App\Model\Gift;
function apiGiftHas($key, $value) {
  $vendorInfo = session('admpvUser');
  return boolval(Gift::where([$key => $value, 'vendor_id' => $vendorInfo['id']])->first());
}
